package com.lumlord.log;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.ConsoleAppender;

import com.lumlord.util.SyncLog;
import org.assertj.core.util.DateUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class InfluxConsoleAppender<E> extends ConsoleAppender<E> {
    @Override
    protected void subAppend(E event) {
        if (event instanceof LoggingEvent) {
            LoggingEvent eventObject = (LoggingEvent) event;
            byte[] byteArray = this.encoder.encode(event);

            LogEntity log = new LogEntity(
                    SyncLog.staticSpringApplicationName,
                    eventObject.getLoggerName(),
                    eventObject.getMessage(),
                    eventObject.getThreadName(),
                    eventObject.getTimeStamp(),
                    eventObject.getLevel().toString(),
                    new String(byteArray));
            insterLog(log);
        }

        super.subAppend(event);

    }

    //Marker marker, String fqcn, int levelInt, String message, Object[] argArray, Throwable t
    private void insterLog(LogEntity log) {
        Map tags = new HashMap<>();
        tags.put("clazz", log.getClazz());

        Map fields = new HashMap<>();
        fields.put("message", log.getMessage());
        fields.put("levelInt", log.getLevel());
        fields.put("threadName", log.getThreadName());
        fields.put("logTime", DateUtil.newTimestampDateFormat().format(new Date(log.getTimeStamp())));
        fields.put("serverName", log.getServerName());
        fields.put("info", log.getInfo());

        SyncLog.log(tags, fields, log.getClazz(),false);
    }


}

